<template>
  <el-drawer
    v-model="runSqlDrawer"
    :title="title"
    :with-header="true"
    :append-to-body="true"
    :show-close="true"
  >
    <div>
      <el-form
        ref="testFormRef"
        :model="testFormData"
        label-width="auto"
        :rules="testFormRules"
        label-position="top"
      >
        <el-form-item prop="param" class="sqlLabel">
          <template #label>
            <span> sql参数: </span>
            <el-tooltip content='格式必须如下 : {"id": "1"}' placement="right">
              <el-icon class="sqlParamTip"><question-filled /></el-icon>
            </el-tooltip>
            <el-button
              size="small"
              type="primary"
              plain
              @click="formatParam"
              style="float: right"
              >格式化参数</el-button
            >
          </template>
          <el-input
            v-model="testFormData.param"
            placeholder="sql参数"
            class="demoWidth"
            clearable
            :rows="testFormData.paramKeyLength"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="sql文本: " prop="sql">
          <el-input
            :disabled="sqlId"
            v-model="testFormData.sqlText"
            placeholder="sql文本"
            clearable
            :rows="3"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        size="small"
        style="float: right"
        @click="testSql"
        >运 行</el-button
      >
    </div>
    <div v-show="testSqlVisable" style="margin-top: 50px">
      <p>运行结果:</p>
      <el-divider />
      <el-input
        disabled
        :value="testRunSqlReturnDataList"
        class="demoWidth"
        clearable
        :rows="6"
        type="textarea"
      ></el-input>
    </div>
  </el-drawer>
</template>
<script>
import {
  sqlTest,
  getSqlById,
  runSql,
} from "@/api/system/sql";
export default {
  props: {
    sqlText:String
  },
  data() {
    return {
      title:"",
      sqlId:undefined, // 运行的sql id
      // sql运行抽屉开关
      runSqlDrawer: false,
      // sql运行抽屉表单数据对象
      testFormData: {
        sqlText: "",
        param: "",
        paramKeyLength:0,
      },
      // sql运行结果是否展示开关
      testSqlVisable: false,
      // sql运行结果
      testRunSqlReturnDataList: [],
      // sql运行抽屉表单校验规则
      testFormRules: {
        sqlText: [
          { required: true, trigger: "blur", message: "sql文本不能为空" },
        ],
      },
    };
  },
  methods: {
    // 打开sql运行抽屉事件
    async openRunModal(id) {
      // 先清空
      this.sqlId = undefined
      this.sqlId = id
      if (id) {
        this.title="运行窗口"
        await getSqlById({"id":id}).then(res=>{
          if (res.code==1) {
            this.testFormData.sqlText = res.data.sqlText
          }
        })
      } else {
        this.title="试运行窗口"
        this.testFormData.sqlText = this.sqlText;
      }
      this.runSqlDrawer = true;
      this.testFormData.param = "";
      this.testRunSqlReturnDataList = [];
      this.getSqlPlaceholder()
    },
    // 获取sql中的占位符 , 组装成参数,回显在sql参数框中
    getSqlPlaceholder(){
      // 匹配sql中的占位符
      const regex = /[#{|${]\w+}/g; 
      let matches = this.testFormData.sqlText.match(regex)
      if (matches && matches!=null && matches.length > 0) {
        let params = {}
        matches.forEach(p=>{
          let param = p.replace("#","").replace("$","").replace("{","").replace("}","")
          params[param] = ""
        })
        this.testFormData.paramKeyLength = matches.length+2;
        // 参数文本域最少3行
        if (this.testFormData.paramKeyLength<3) {
          this.testFormData.paramKeyLength = 3
        }
        this.testFormData.param = JSON.stringify(params, null, 2);
      }
    },
    // 试运行sql
    testSql() {
      this.$refs["testFormRef"].validate(async (valid) => {
        if (valid) {
          try {
            let param = this.testFormData.param;
            // sql参数格式化之后的数据
            let params = {};
            // 不为空,格式化成json对象
            if (param && param.trim().length > 0) {
              params = JSON.parse(this.testFormData.param);
            }
            if (this.sqlId) {
              // 正式运行
              runSql(this.sqlId, params).then((res) => {
                this.testRunSqlReturnDataList = [];
                if (res.code == 1) {
                  this.testSqlVisable = true;
                  this.testRunSqlReturnDataList = JSON.stringify(res.data);
                }
              });
            } else {
              // 测试运行
              sqlTest(this.testFormData.sqlText, params).then((res) => {
                this.testRunSqlReturnDataList = [];
                if (res.code == 1) {
                  this.testSqlVisable = true;
                  this.testRunSqlReturnDataList = JSON.stringify(res.data);
                }
              });
            }
          } catch (error) {
            this.$message.error("sql参数格式化错误");
          }
        }
      });
    },
    // 格式化参数
    formatParam() {
      if (this.testFormData.param && this.testFormData.param.length > 0) {
        try {
          let taskParm = JSON.parse(this.testFormData.param);
          this.testFormData.param = JSON.stringify(taskParm, null, 2);
        } catch (error) {
          this.$message.error("参数格式化错误, 请检查SQL参数");
        }
      }
    },
  },
};
</script>
<style></style>
